package com.dji.sample.component.event;


import com.dji.sample.common.model.CacheModel;
import com.dji.sample.manage.dao.IDeviceMapper;
import com.dji.sample.manage.model.dto.DeviceDTO;
import com.dji.sample.manage.model.enums.DeviceDomainEnum;
import com.dji.sample.manage.model.enums.DeviceStatusEnum;
import com.dji.sample.manage.service.DevicePlayLineInfoService;
import com.dji.sample.manage.service.IDeviceService;
import com.dji.sample.manage.service.impl.DevicesPositionOSDServiceImpl;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

/**
 * @author yjt
 * @date 2022-09-09
 * @description:
 */
@Log4j2
@Component
public class DeviceStatusChangeListener {

    @Autowired
    DevicePlayLineInfoService devicePlayLineInfoService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    IDeviceService deviceService;

    private static String FLIGHT_PLAY_KEY = "flight:device:";

    @Async
    @EventListener
    public void listener(DeviceStatusChangeEvent event) throws InterruptedException {
        if (Objects.equals(event.getStatus(), DeviceStatusEnum.OFFLINE.getVal())) {
            //设备下线
            String key = String.format("%s%s", "device:osd:position:", event.getDeviceSn());
            CacheModel.get(event.getCacheKey()).remove(key);
            Optional<DeviceDTO> deviceDTO = deviceService.getDeviceBySn(event.getDeviceSn());
            if (deviceDTO.isPresent() && deviceDTO.get().getDomain().equals(DeviceDomainEnum.SUB_DEVICE.getDesc())) {
                devicePlayLineInfoService.updatePosition(event.getDeviceSn());
            }
            deviceDTO.ifPresent(dto -> redisTemplate.delete(FLIGHT_PLAY_KEY + dto.getDeviceSn()));
        }
        if (Objects.equals(event.getStatus(), DeviceStatusEnum.ONLINE.getVal())) {
            String key = "device:online:listener:" + event.getDeviceSn();
            //没有新增 有续约
            if (Boolean.TRUE.equals(redisTemplate.hasKey(key))) {
                redisTemplate.opsForValue().set(key, "1", 1, TimeUnit.MINUTES);
                return;
            }
            Optional<DeviceDTO> deviceDTO = deviceService.getDeviceBySn(event.getDeviceSn());
            if (deviceDTO.isPresent() && deviceDTO.get().getDomain().equals(DeviceDomainEnum.SUB_DEVICE.getDesc())) {
                devicePlayLineInfoService.save(event.getDeviceSn());
            }
            redisTemplate.opsForValue().set(key, "1", 1, TimeUnit.MINUTES);
        }
        log.info("监听到数据：{}", event.getMessage());
    }

}
